package a66weding.com.jiehuntong.pager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.andview.refreshview.XRefreshView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.ToolsGiftAddGiftActivity;
import a66weding.com.jiehuntong.activity.ToolsGiftsActivity;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.GiftBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.CommonAdapter;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.MyViewHolder;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.view.ConfirmDialog;
import a66weding.com.jiehuntong.view.SwipteLayout2;
/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/6/2
 * @description :
 */
public class ToolsPager_Gift_Home extends BasePager implements View.OnClickListener, OnNetResultListener {
    private ToolsGiftsActivity mGiftActivity;
    private View mContentview;
    private TextView mEmptyAddTv;
    private LinearLayout mEmptyLay;
    private LinearLayout mContentLay;
    private ListView mGiftlview;
    private TextView mAccountTv;
    private TextView mGiftSumTv;
    private ImageButton mAddGiftIvbtn;
    private LinearLayout mBackLay;
    private ProgressBar mProgressbar;
    private List<GiftBean.DataBean> mGiftList = new ArrayList<>();
    private int mCurrentPosition;
    private CommonAdapter mGiftAdapter;
    private int screenheight;
    private int btnwidth;
    private int btnheight;
    private GiftBean.DataBean dataBean;
    private float mAccontGift;
    private SwipteLayout2 mSwipeLay;
    private XRefreshView xRefreshView;
    private boolean isDownRefresh;
    public ToolsPager_Gift_Home(Activity activity) {
        super(activity);
    }
    @Override
    protected View getView() {
        mGiftActivity = (ToolsGiftsActivity) mActivity;
        mContentview = View.inflate(mActivity, R.layout.tools_gift_home, null);
        mEmptyAddTv = (TextView) mContentview.findViewById(R.id.tv_tools_gift_addgift);
        mEmptyLay = (LinearLayout) mContentview.findViewById(R.id.llay_tools_gift_emptygift);
        mGiftlview = (ListView) mContentview.findViewById(R.id.lview_tools_gift);
        mContentLay = (LinearLayout) mContentview.findViewById(R.id.llay_tools_giftcontent);
        mAccountTv = (TextView) mContentview.findViewById(R.id.label_receive_account);
        mGiftSumTv = (TextView) mContentview.findViewById(R.id.label_sum);
        mAddGiftIvbtn = (ImageButton) mContentview.findViewById(R.id.btn_tools_addgift);
        mBackLay = (LinearLayout) mContentview.findViewById(R.id.llay_toolsheader_back);
        mProgressbar = (ProgressBar) mContentview.findViewById(R.id.progressBar);
        xRefreshView = (XRefreshView) mContentview.findViewById(R.id.tools_gift_xrefreshview);
        initRefreshView();
        mEmptyAddTv.setOnClickListener(this);
        mAddGiftIvbtn.setOnClickListener(this);
        mBackLay.setOnClickListener(this);
        mEmptyLay.setVisibility(View.GONE);
        return mContentview;
    }

    @Override
    public void initData() {
        EventBus eventBus = EventBus.getDefault();
        eventBus.register(this);
        btnwidth = mAddGiftIvbtn.getWidth();
        btnheight = mAddGiftIvbtn.getHeight();
        WindowManager wm = (WindowManager) mGiftActivity.getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = wm.getDefaultDisplay();
        screenheight = defaultDisplay.getHeight();
        getGiftData();
    }

    private void getGiftData() {
        String url = UrlDealUtil.getRealUrl(RequestCode.RETURN_BOOKENTRY);
        HttpRequestBean httpBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, GiftBean.class, RequestCode.RETURN_BOOKENTRY);
        HttpHandleUtil.executeCommonPost(mGiftActivity, httpBean);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_tools_gift_addgift:
                mGiftActivity.setEditGift(false);
                startAddGiftActivity();
                break;
            case R.id.btn_delete://删除礼金item
                mCurrentPosition = (int) view.getTag();
                dataBean = mGiftList.get(mCurrentPosition);
                showDialog(mGiftActivity, "您确定要删除吗？", "确定", "取消");
                break;
            case R.id.btn_tools_addgift://添加礼金
                mGiftActivity.setEditGift(false);
                startAddGiftActivity();
                break;
            case R.id.llay_giftitem_content://修改,编辑礼金
                mGiftActivity.setEditGift(true);
                mCurrentPosition = (int) view.getTag();
                GiftBean.DataBean dataBean2 = mGiftList.get(mCurrentPosition);
                boolean iseditGift = mGiftActivity.isEditGift();
                Intent intent = new Intent(mGiftActivity, ToolsGiftAddGiftActivity.class);
                intent.putExtra("isEdit", iseditGift);
                Bundle bundle = new Bundle();
                bundle.putSerializable("DataBean", dataBean2);
                intent.putExtras(bundle);
                mGiftActivity.startActivity(intent);
                break;
            case R.id.llay_toolsheader_back://返回
                mGiftActivity.getSupportFragmentManager().popBackStack();
                mGiftActivity.finish();
                break;
        }
    }


    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (isDownRefresh) {
            xRefreshView.stopRefresh();
        }
        if (data instanceof GiftBean) {
            GiftBean mGiftBean = (GiftBean) data;
            switch (mGiftBean.getResCode()) {
                case "0000":
                    mProgressbar.setVisibility(View.GONE);
                    mAddGiftIvbtn.setVisibility(View.VISIBLE);
                    mGiftList = mGiftBean.getData();
                    mContentLay.setVisibility(View.VISIBLE);
                    int size = mGiftList.size();
                    if (size < 1) {
                        mEmptyLay.setVisibility(View.VISIBLE);
                        return;
                    }
                    mAccountTv.setText("共收到" + size + "份礼金");
                    double cashGiftAmount = 0.0f;
                    for (int i = 0; i < size; i++) {
                        cashGiftAmount += mGiftList.get(i).getCashGiftAmount();
                    }
                    mGiftSumTv.setText("￥ " + (int) cashGiftAmount);
                    mGiftAdapter = new CommonAdapter<GiftBean.DataBean>(mGiftActivity, mGiftList, R.layout.item_tools_gift_contentitem) {
                        @Override
                        public void convert(MyViewHolder holder, int position) {
                            GiftBean.DataBean dataBean = mGiftList.get(position);
                            String cashGiftRemark = dataBean.getCashGiftRemark();
                            TextView remarkTv = (TextView) holder.getView(R.id.remark);
                            if (TextUtils.isEmpty(cashGiftRemark)) {
                                remarkTv.setVisibility(View.GONE);
                            } else {
                                remarkTv.setVisibility(View.VISIBLE);
                                remarkTv.setText(cashGiftRemark);
                            }
                            double cashGiftAmount2 = dataBean.getCashGiftAmount();
                            NumberFormat nf3 = NumberFormat.getInstance();
                            nf3.setGroupingUsed(false);
                            String format3 = nf3.format(cashGiftAmount2);
                            holder.setText(R.id.account, "￥ " + format3);
                            holder.setText(R.id.data, dataBean.getCashGiftName());
                            Button delBtn = (Button) holder.getView(R.id.btn_delete);
                            LinearLayout mContentLay = (LinearLayout) holder.getView(R.id.llay_giftitem_content);
                            SwipteLayout2 mSwipLay = (SwipteLayout2) holder.getView(R.id.llay_tools_dayplan_mainitem);
                            delBtn.setTag(position);
                            delBtn.setOnClickListener(ToolsPager_Gift_Home.this);
                            mContentLay.setTag(position);
                            mContentLay.setOnClickListener(ToolsPager_Gift_Home.this);
                            mSwipLay.setOnItemStateChanged(new SwipteLayout2.OnItemStateChanged() {
                                @Override
                                public void onOpen(SwipteLayout2 layout) {
                                    mSwipeLay = layout;
                                }

                                @Override
                                public void onClose(SwipteLayout2 layout) {
                                    if (mSwipeLay == layout) {
                                        mSwipeLay = null;
                                    }
                                }

                                @Override
                                public void onDown(SwipteLayout2 layout) {
                                    if (mSwipeLay != null && mSwipeLay != layout) {
                                        mSwipeLay.closeMenu();
                                    }
                                }
                            });

                        }
                    };
                    mGiftlview.setAdapter(mGiftAdapter);
                    mGiftlview.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View view, MotionEvent motionEvent) {
                            if (motionEvent.getAction()==motionEvent.ACTION_MOVE){
                                startAnimation(mAddGiftIvbtn, false);
                            }else if (motionEvent.getAction()==motionEvent.ACTION_UP){
                                startAnimation(mAddGiftIvbtn, true);
                            }
                            return false;
                        }
                    });
                    mEmptyLay.setVisibility(View.GONE);
                    break;
                case "0001":
                case "0002":
                case "0003":
                    mProgressbar.setVisibility(View.GONE);
                    mAddGiftIvbtn.setVisibility(View.GONE);
                    mEmptyLay.setVisibility(View.VISIBLE);
                    break;
            }
        } else if (data instanceof CommonResultBean) {
            CommonResultBean commonResult = (CommonResultBean) data;
            switch (commonResult.getResCode()) {
                case "0000":
                    mGiftList.remove(mCurrentPosition);
                    for (int i = 0; i < mGiftList.size(); i++) {
                        mAccontGift += mGiftList.get(i).getCashGiftAmount();
                    }
                    mAccountTv.setText("共收到" + mGiftList.size() + "份礼金");
                    mGiftSumTv.setText("￥ " + (int) mAccontGift);

                    if (mGiftAdapter != null) {
                        mGiftAdapter.notifyDataSetChanged();
                    }
                    if (mSwipeLay != null) {
                        mSwipeLay.closeMenu();
                    }
                    if (mGiftList.size() == 0) {
                        mContentLay.setVisibility(View.GONE);
                        mEmptyLay.setVisibility(View.VISIBLE);
                        mAddGiftIvbtn.setVisibility(View.GONE);
                        mAccontGift = 0;
                    }
                    break;
                case "0001":
                case "0002":
                case "0003":
                    mProgressbar.setVisibility(View.GONE);
                    mAddGiftIvbtn.setVisibility(View.GONE);
                    mEmptyLay.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
    }
    public void startAddGiftActivity() {
        boolean iseditGift = mGiftActivity.isEditGift();
        Intent intent = new Intent(mGiftActivity, ToolsGiftAddGiftActivity.class);
        intent.putExtra("isEdit", iseditGift);
        mGiftActivity.startActivity(intent);
    }

    public void startAnimation(View view, boolean isreturn) {
        Animation mAnima = null;
        if (isreturn) {
            mAnima = new TranslateAnimation(0, 0, Utils.getScreenWidth(mActivity), 0);
            mAnima.setDuration(500);
        } else {
            mAnima = new TranslateAnimation(0, 0, btnheight, screenheight);
            mAnima.setDuration(1500);
        }
        view.startAnimation(mAnima);
    }

    @Subscribe
    public void onEvent(MessageEvent event) {
        GiftBean.DataBean giftData = event.getGiftData();
        if (giftData != null) {
            int cashGiftID1 = giftData.getCashGiftID();
            Log.e("Log", "ToolsPager_Gift_Home onEvent: giftData=" + giftData.getCashGiftID());
            for (int i = 0; i < mGiftList.size(); i++) {
                int cashGiftID = mGiftList.get(i).getCashGiftID();
                if (cashGiftID == cashGiftID1) {
                    mGiftList.remove(i);
                    mGiftList.add(i, giftData);
                }
                if (mGiftAdapter != null) {
                    mGiftAdapter.notifyDataSetChanged();
                }
            }
        } else {
            getGiftData();
        }
    }

    //初始化上啦刷新
    private void initRefreshView() {
        //是否允许下拉刷新
        xRefreshView.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        xRefreshView.setPullLoadEnable(false);
        // 设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        // 静默加载模式不能设置footerview
        // 设置支持自动刷新
        xRefreshView.setAutoLoadMore(false);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh() {
                isDownRefresh = true;
                getGiftData();

            }

        });
    }

    public void showDialog(Context context, String title, String confirm, String cancel) {
        final ConfirmDialog confirmDialog = new ConfirmDialog(context, title, confirm, cancel, R.layout.confirm_dialog);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                String url = UrlDealUtil.getRealUrl(RequestCode.DELECT_CASHGIFT);
                HashMap<String, String> requestParams = new HashMap<String, String>();
                requestParams.put("CashGiftID", "" + dataBean.getCashGiftID());
                HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                        ToolsPager_Gift_Home.this, CommonResultBean.class, RequestCode.DELECT_CASHGIFT, requestParams);
                HttpHandleUtil.executeCommonPost(mGiftActivity, httpRequestBean);
                confirmDialog.dismiss();
            }
            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }
}
